import json
import os
from datetime import datetime
from passlib.context import CryptContext

abs_path = os.path.abspath(__file__)

basedir = os.path.dirname(os.path.dirname(os.path.dirname(abs_path)))


def storage_path(path: str = ''):
    return os.path.join(basedir, f'storage/{path}')


def public_path(path: str = ''):
    return os.path.join(basedir, f'public/{path}')


def upload_file_path(path: str = ''):
    return os.path.join(basedir, f'{path}')


class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")  # 将 datetime 格式化为字符串
        return super().default(obj)


def list_to_json(query_list: list):
    return [post.dict() for post in query_list]


def datetime_to_str(obj):
    if isinstance(obj, datetime):
        return obj.strftime('%Y-%m-%d %H:%M:%S')


# 创建一个 CryptContext 实例
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


# 哈希密码
def hash_password(password: str) -> str:
    return pwd_context.hash(password)


# 验证密码
def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)
